package com.mbsnjdxyry.tracord_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mbsnjdxyry.tracord_backend.common.CityUtils;
import com.mbsnjdxyry.tracord_backend.common.ResponseResult;
import com.mbsnjdxyry.tracord_backend.common.ResultCode;
import com.mbsnjdxyry.tracord_backend.domain.PassageFollowerNum;
import com.mbsnjdxyry.tracord_backend.domain.PassageInfo;
import com.mbsnjdxyry.tracord_backend.domain.User;
import com.mbsnjdxyry.tracord_backend.domain.UserFollowInfo;
import com.mbsnjdxyry.tracord_backend.domain.vo.PassageToFront;
import com.mbsnjdxyry.tracord_backend.domain.vo.UserToFront;
import com.mbsnjdxyry.tracord_backend.mapper.PassageFollowerNumMapper;
import com.mbsnjdxyry.tracord_backend.mapper.PassageInfoMapper;
import com.mbsnjdxyry.tracord_backend.mapper.UserFollowInfoMapper;
import com.mbsnjdxyry.tracord_backend.mapper.UserMapper;
import com.mbsnjdxyry.tracord_backend.service.PassageService;
import com.mbsnjdxyry.tracord_backend.utils.PassageToFrontConverter;
import com.mbsnjdxyry.tracord_backend.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 帖子服务实现类
 * @date 2023/05/21
 * @auther linorman
 */
@Service
public class PassageServiceImpl extends ServiceImpl<PassageInfoMapper, PassageInfo> implements PassageService {
    @Autowired
    private PassageInfoMapper passageInfoMapper;

    @Autowired
    private PassageFollowerNumMapper passageFollowerNumMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserFollowInfoMapper userFollowInfoMapper;

    @Autowired
    private PassageToFrontConverter passageToFrontConverter;

    /**
     * 用于社区展示的文章列表
     * @return
     */
    @Override
    public ResponseResult<List<PassageToFront>> getPassageList() {
        LambdaQueryWrapper<PassageInfo> queryWrapper = new LambdaQueryWrapper<>();
        List<PassageInfo> passageInfoList = passageInfoMapper.selectList(queryWrapper);
        if (passageInfoList.isEmpty()){
            return ResponseResult.error(ResultCode.PASSAGE_LIST_NULL,null);
        }
        //List<PassageToFront> passageToFrontList = new ArrayList<>();
        List<PassageToFront> passageToFrontList = passageToFrontConverter.getPassageToFrontList(passageInfoList);
//        for (PassageInfo passageInfo : passageInfoList) {
//            User user = userMapper.selectById(passageInfo.getUserId());
//            PassageToFront passageToFront = new PassageToFront();
//            passageToFront.setAvatar(user.getAvatar());
//            passageToFront.setNickname(user.getNickName());
//            passageToFront.setId(passageInfo.getId());
//            passageToFront.setUserId(passageInfo.getUserId());
//            passageToFront.setContent(passageInfo.getContent());
//            passageToFront.setAddress(passageInfo.getAddress());
//            passageToFront.setPhotoTime(passageInfo.getPhotoTime());
//            passageToFront.setCreateDate(passageInfo.getCreateDate());
//            passageToFront.setImage(passageInfo.getImage());
//            passageToFront.setFollowerNum(passageInfo.getFollowerNum());
//
//            LambdaQueryWrapper<PassageFollowerNum> queryWrapper1 = new LambdaQueryWrapper<>();
//            queryWrapper1.eq(PassageFollowerNum::getPassageId,passageInfo.getId());
//            List<PassageFollowerNum> passageFollowerNumList = passageFollowerNumMapper.selectList(queryWrapper1);
//            if (passageFollowerNumList.isEmpty()){
//                passageToFront.setFollowerNum(0);
//            }else {
//                passageToFront.setFollowerNum(passageFollowerNumList.size());
//            }
//
//            //查询当前用户是否点赞了该帖子
//            LambdaQueryWrapper<PassageFollowerNum> lqw = new LambdaQueryWrapper<>();
//            lqw.eq(PassageFollowerNum::getPassageId,passageInfo.getId())
//                    .eq(PassageFollowerNum::getFollowerId,SecurityUtils.getUserId());
//            PassageFollowerNum res = passageFollowerNumMapper.selectOne(lqw);
//            if(Objects.isNull(res)){
//                passageToFront.setIsFollowed(0);
//            }else {
//                passageToFront.setIsFollowed(1);
//            }
//
//            //查询当前用户是否关注了该帖子的博主
//            LambdaQueryWrapper<UserFollowInfo> lqw2 = new LambdaQueryWrapper<>();
//            lqw2.eq(UserFollowInfo::getFollowerId,passageInfo.getUserId())
//                    .eq(UserFollowInfo::getUserId,SecurityUtils.getUserId());
//            Integer res2 = userFollowInfoMapper.selectCount(lqw2);
//            if(res2 > 0){
//                passageToFront.setIsUserFollowed(1);
//            }else {
//                passageToFront.setIsUserFollowed(0);
//            }
//
//            List<UserToFront> userToFrontList = new ArrayList<>();
//            for (int i = 0; i < passageFollowerNumList.size(); i++) {
//                //展示前三个点赞的用户
//                if (i == 3) {
//                    break;
//                }
//                LambdaQueryWrapper<User> queryWrapper2 = new LambdaQueryWrapper<>();
//                queryWrapper2.eq(User::getId, passageFollowerNumList.get(i).getFollowerId());
//                User user1 = userMapper.selectOne(queryWrapper2);
//                userToFrontList.add(new UserToFront(user1.getId(),user1.getAvatar()));
//            }
//            passageToFront.setUserList(userToFrontList);
//            passageToFrontList.add(passageToFront);
//        }

        return ResponseResult.success(ResultCode.PASSAGE_LIST_GET_SUCCESS,passageToFrontList);
    }

    /**
     * 获得当前用户所写的文章
     * @return
     */
    @Override
    public ResponseResult<List<PassageToFront>> getUserPassageList() {
        Integer userId = SecurityUtils.getUserId();

        LambdaQueryWrapper<PassageInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PassageInfo::getUserId,userId);

        List<PassageInfo> passageInfoList = passageInfoMapper.selectList(queryWrapper);
        if (passageInfoList.isEmpty()){
            return ResponseResult.error(ResultCode.PASSAGE_LIST_NULL,null);
        }

        //List<PassageToFront> passageToFrontList = new ArrayList<>();
        List<PassageToFront> passageToFrontList = passageToFrontConverter.getPassageToFrontList(passageInfoList);

        return ResponseResult.success(ResultCode.PASSAGE_LIST_GET_SUCCESS,passageToFrontList);
    }

    /**
     * 根据 id 获取用户帖子列表
     * @param id
     * @return
     */
    @Override
    public ResponseResult<List<PassageToFront>> getUserPassageListByUserId(Integer id) {
        LambdaQueryWrapper<PassageInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PassageInfo::getUserId,id);

        List<PassageInfo> passageInfoList = passageInfoMapper.selectList(queryWrapper);
        if (passageInfoList.isEmpty()){
            return ResponseResult.error(ResultCode.PASSAGE_LIST_NULL,null);
        }

        //List<PassageToFront> passageToFrontList = new ArrayList<>();
        List<PassageToFront> passageToFrontList = passageToFrontConverter.getPassageToFrontList(passageInfoList);

        return ResponseResult.success(ResultCode.PASSAGE_LIST_GET_SUCCESS,passageToFrontList);
    }

    /**
     * 根据文章 id 查询文章
     * @param passageInfo
     * @return
     */
    @Override
    public ResponseResult<PassageInfo> getPassageById(PassageInfo passageInfo) {
        LambdaQueryWrapper<PassageInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PassageInfo::getId,passageInfo.getId());
        PassageInfo passageInfo1 = passageInfoMapper.selectOne(queryWrapper);
        if (passageInfo1 == null){
            return ResponseResult.error(ResultCode.PASSAGE_GET_ERROR,null);
        }
        return ResponseResult.success(ResultCode.PASSAGE_GET_SUCCESS,passageInfo1);
    }

    /**
     * 发布帖子
     * @param passageInfo
     * @return
     */
    @Override
    public ResponseResult publishPassage(PassageInfo passageInfo) {
        Integer userId = SecurityUtils.getUserId();
        passageInfo.setUserId(userId);
        int result = passageInfoMapper.insert(passageInfo);
        if (result == 0){
            return ResponseResult.error(ResultCode.PASSAGE_ADD_ERROR,null);
        }
        return ResponseResult.success(ResultCode.PASSAGE_ADD_SUCCESS,null);
    }

    /**
     * 删除帖子
     * @param passageInfo
     * @return
     */
    @Override
    public ResponseResult<PassageInfo> deletePassage(PassageInfo passageInfo) {
        //除了删除文章
        LambdaQueryWrapper<PassageInfo> passageLqw = new LambdaQueryWrapper<>();
        passageLqw.eq(PassageInfo::getId,passageInfo.getId());

        //还要删除点赞信息
        LambdaQueryWrapper<PassageFollowerNum> followLqw = new LambdaQueryWrapper<>();
        followLqw.eq(PassageFollowerNum::getPassageId,passageInfo.getId());

        int result1 = passageInfoMapper.delete(passageLqw);
        int result2 = passageFollowerNumMapper.delete(followLqw);

        if (result1 == 0 || result2 == 0){
            return ResponseResult.error(ResultCode.PASSAGE_DELETE_ERROR,null);
        }

        return ResponseResult.success(ResultCode.PASSAGE_DELETE_SUCCESS,null);
    }

    /**
     * 点赞帖子
     * @param userId, passageId
     * @param passageId
     * @return
     */
    @Override
    public ResponseResult followPassage(Integer userId, Integer passageId) {
        PassageFollowerNum passageFollowerNum = new PassageFollowerNum();
        passageFollowerNum.setFollowerId(userId);
        passageFollowerNum.setPassageId(passageId);
        int result = passageFollowerNumMapper.insert(passageFollowerNum);
        if (result == 0){
            return ResponseResult.error(ResultCode.PASSAGE_LIKE_ERROR,null);
        }
        LambdaQueryWrapper<PassageInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PassageInfo::getId,passageId);
        PassageInfo passageInfo = passageInfoMapper.selectOne(queryWrapper);
        passageInfo.setFollowerNum(passageInfo.getFollowerNum()+1);
        passageInfoMapper.updateById(passageInfo);
        return ResponseResult.success(ResultCode.PASSAGE_LIKE_SUCCESS,null);
    }

    /**
     * 取消点赞帖子
     * @param userId, passageId
     * @param passageId
     * @return
     */
    @Override
    public ResponseResult unfollowPassage(Integer userId, Integer passageId) {
        LambdaQueryWrapper<PassageFollowerNum> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PassageFollowerNum::getFollowerId,userId);
        queryWrapper.eq(PassageFollowerNum::getPassageId,passageId);
        int result = passageFollowerNumMapper.delete(queryWrapper);
        if (result == 0){
            return ResponseResult.error(ResultCode.PASSAGE_CANCEL_LIKE_ERROR,null);
        }
        LambdaQueryWrapper<PassageInfo> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(PassageInfo::getId,passageId);
        PassageInfo passageInfo = passageInfoMapper.selectOne(queryWrapper1);
        passageInfo.setFollowerNum(passageInfo.getFollowerNum()-1);
        passageInfoMapper.updateById(passageInfo);
        return ResponseResult.success(ResultCode.PASSAGE_CANCEL_LIKE_SUCCESS,null);
    }

    /**
     * 获得文章点赞数
     * @param passageInfo
     * @return
     */
    @Override
    public ResponseResult<Integer> getPassageFollowerNum(PassageInfo passageInfo) {
        LambdaQueryWrapper<PassageFollowerNum> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PassageFollowerNum::getPassageId,passageInfo.getId());
        List<PassageFollowerNum> passageFollowerNumList = passageFollowerNumMapper.selectList(queryWrapper);
        if (passageFollowerNumList.isEmpty()){
            return ResponseResult.success(ResultCode.PASSAGE_FOLLOWER_NUM_GET_SUCCESS,0);
        }
        return ResponseResult.success(ResultCode.PASSAGE_FOLLOWER_NUM_GET_SUCCESS,passageFollowerNumList.size());
    }

    /**
     * 根据地址返回文章列表
     * @param address
     * @return
     */
    @Override
    public ResponseResult<List<PassageToFront>> getPassageListByAddress(String address) {
        LambdaQueryWrapper<PassageInfo> queryWrapper = new LambdaQueryWrapper<>();
        boolean flag = true;
        for (int i = 0; i < CityUtils.CITY_NAMES.length; i++) {
            if (address.contains(CityUtils.CITY_NAMES[i])){
                address = CityUtils.CITY_NAMES[i];
                flag = false;
                break;
            }
        }
        if (!flag){
            for (int i = 0; i < CityUtils.PROVINCE.length; i++) {
                if (address.contains(CityUtils.PROVINCE[i])) {
                    address = CityUtils.getCityByProvince(CityUtils.PROVINCE[i]);
                    flag = true;
                    break;
                }
            }
        }

        queryWrapper.like(PassageInfo::getAddress,address);
        List<PassageInfo> passageInfoList = passageInfoMapper.selectList(queryWrapper);

        if (passageInfoList.isEmpty()){
            return ResponseResult.error(ResultCode.PASSAGE_LIST_GET_ERROR,null);
        }

        //List<PassageToFront> passageToFrontList = new ArrayList<>();
        List<PassageToFront> passageToFrontList = passageToFrontConverter.getPassageToFrontList(passageInfoList);

        return ResponseResult.success(ResultCode.PASSAGE_LIST_GET_SUCCESS,passageToFrontList);
    }

    /**
     * 获取用户所获点赞总量
     * @param userId
     * @return
     */
    @Override
    public ResponseResult getTotalFollowerNum(Integer userId) {
        LambdaQueryWrapper<PassageInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PassageInfo::getUserId,userId);
        List<PassageInfo> passageInfoList = passageInfoMapper.selectList(queryWrapper);
        if (passageInfoList.isEmpty()){
            return ResponseResult.success(ResultCode.PASSAGE_FOLLOWER_NUM_GET_SUCCESS,0);
        }
        int sum = 0;
        for (int i = 0; i < passageInfoList.size(); i++) {
            sum += passageInfoList.get(i).getFollowerNum();
        }
        return ResponseResult.success(ResultCode.PASSAGE_FOLLOWER_NUM_GET_SUCCESS,sum);
    }

    /**
     * 获取用户发表的帖子总数
     * @param userId
     * @return
     */
    @Override
    public ResponseResult getUserPassageNum(Integer userId) {
        LambdaQueryWrapper<PassageInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PassageInfo::getUserId,userId);
        List<PassageInfo> passageInfoList = passageInfoMapper.selectList(queryWrapper);
        if (passageInfoList.isEmpty()){
            return ResponseResult.success(ResultCode.PASSAGE_NUM_GET_SUCCESS,0);
        }
        return ResponseResult.success(ResultCode.PASSAGE_NUM_GET_SUCCESS,passageInfoList.size());
    }

    /**
     * 根据用户昵称模糊查询帖子
     * @param nickname
     * @return
     */
    @Override
    public ResponseResult getPassageListByUserNickname(String nickname) {
        LambdaQueryWrapper<User> userLqw = new LambdaQueryWrapper();
        userLqw.like(User::getNickName,nickname);
        List<User> userList = userMapper.selectList(userLqw);
        List<PassageInfo> passageInfoList = new ArrayList<>();
        for (User user : userList) {
            LambdaQueryWrapper<PassageInfo> passageLqw = new LambdaQueryWrapper<>();
            passageLqw.eq(PassageInfo::getUserId,user.getId());
            List<PassageInfo> tempList = passageInfoMapper.selectList(passageLqw);
            passageInfoList.addAll(tempList);
        }

        List<PassageToFront> passageToFrontList = passageToFrontConverter.getPassageToFrontList(passageInfoList);

        return ResponseResult.success(ResultCode.PASSAGE_LIST_GET_SUCCESS,passageToFrontList);
    }
}
